import Vue from "vue";
import Vuex from "vuex"

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        goods: JSON.parse(localStorage.getItem('goods')) || [],//如果有则从本地读取，没有则为空数组
    },
    mutations: {
        //加入购物车
        addCart(state, payload) {
            const product = state.goods.find(item => item.iid == payload.iid)
            if (product) {
                product.count++
            } else {
                state.goods.push(Object.assign({
                    "count": 1,
                    "checked": true, //默认选中
                }, payload))
            }
        },

        // 删除商品
        delGoods(state) {
            const list = state.goods.filter(item => item.checked == false)
            state.goods = list;
        },
        updateCheck(state, payload) { //更新check按钮的状态
            const product = state.goods.find(item => item.iid === payload)
            product.checked = !product.checked

        },

        //根据全选按钮的状态  来改变所有商品的状态
        selectAll(state, payload) {
            state.goods.forEach(item => item.checked = payload)
        },
    },
    actions: {

    },
    getters: {
        //获取单个商品的数量
        getSingleMount(state) {
            return function (iid) {
                const product = state.goods.find(item => item.iid === iid)
                if (product) {
                    return product.count
                } else {
                    return 0
                }

            }
        },
        // 获取购物车里的商品数量
        getCount(state) {
            return state.goods.length;
        },

        isCheckAll(state) {   //全选按钮是否选中
            // console.log(state,state.products.every(item=>item.checked))
            return state.goods.every(item => item.checked)
        },
        //选中商品的种类数量
        selectedProductsLength(state) {
            return state.goods.filter(item => item.checked).length
        },
        //计算所有选中商品的 价格总和
        total(state) {
            return state.goods.reduce((pre, next) => {
                return pre + (next.checked ? next.count * next.price : 0);
            }, 0)
        }

    },
})
//监听mutations 里面方法的执行  因为一旦方法执行了  state数据一定就改变了
store.subscribe(function (mutations, state) {
    // console.log(arguments)
    //存储数据到本地
    localStorage.setItem('goods', JSON.stringify(state.goods))
})

export default store;